package city.spring.controller.mealService;

import city.spring.domain.entity.mealService.FoodInfoEntity;
import city.spring.domain.entity.mealService.FoodTypeEntity;
import city.spring.service.mealService.FoodInfoService;
import city.spring.service.mealService.FoodTypeService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.google.common.collect.ArrayListMultimap;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/food")
public class FoodApiController extends ApiController {

    /**
     * <strong></strong> Service
     */
    private final FoodTypeService foodTypeService;
    private final FoodInfoService foodInfoService;
    /**
     * 实体类（）可排序字段
     */
    private final List<SFunction<FoodInfoEntity, ?>> entityOrderFields;

    public FoodApiController(FoodTypeService foodTypeService, FoodInfoService foodInfoService) {
        this.foodTypeService = foodTypeService;
        this.foodInfoService = foodInfoService;
        this.entityOrderFields = new ArrayList<>();
        entityOrderFields.add(FoodInfoEntity::getId);
        entityOrderFields.add(FoodInfoEntity::getFoodId);
        entityOrderFields.add(FoodInfoEntity::getFoodName);
        entityOrderFields.add(FoodInfoEntity::getFoodPrize);
        entityOrderFields.add(FoodInfoEntity::getHot);
        entityOrderFields.add(FoodInfoEntity::getTexture);
        entityOrderFields.add(FoodInfoEntity::getTaste);
        entityOrderFields.add(FoodInfoEntity::getDistributionString);
        entityOrderFields.add(FoodInfoEntity::getStartTime);
        entityOrderFields.add(FoodInfoEntity::getEndTime);
        entityOrderFields.add(FoodInfoEntity::getRemarks);
    }

    /**
     * 获取全部的 <strong>食品信息</strong> 列表
     */
    @GetMapping("getAllType")
    public Object getAllType() {
        List<FoodTypeEntity> typeEntities = foodTypeService.list();
        List<FoodInfoEntity> valueEntities = foodInfoService.list();

        ArrayListMultimap<String, FoodInfoEntity> multimap = ArrayListMultimap.create();
        valueEntities.forEach(foodInfoEntity -> multimap.put(foodInfoEntity.getFoodId(), foodInfoEntity));
        typeEntities.forEach(foodTypeEntity ->
                foodTypeEntity.setChildren(multimap.get(foodTypeEntity.getId())));


        return success(typeEntities);
    }

    /**
     * 获取全部的 <strong>食品信息</strong> 列表
     */
    @GetMapping("food-{foodType}")
    public Object listValues(@PageableDefault(sort = {"sorted", "gmtCreate"}) Pageable pageable, FoodInfoEntity entity, @PathVariable String foodType) {
        return success(loadFoodEntity(pageable, entity, foodType).getChildren());
    }

    @NonNull
    private FoodTypeEntity loadFoodEntity(Pageable pageable, FoodInfoEntity entity, String foodType) {
        FoodTypeEntity result;

        List<FoodTypeEntity> foodTypeEntities = foodTypeService.lambdaQuery()
                .eq(FoodTypeEntity::getTypeCode, foodType)
                .or()
                .eq(FoodTypeEntity::getId, foodType)
                .list();

        // 判断查找结果是否为空
        if (foodTypeEntities.isEmpty()) {
            result = new FoodTypeEntity();
            result.setType("未知食品类型");
            result.setChildren(Collections.emptyList());
            return result;
        }

        // 查找食物信息列表信息
        LambdaQueryChainWrapper<FoodInfoEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        if (foodTypeEntities.size() == 1) {
            result = foodTypeEntities.get(0);
            lambdaQuery.eq(FoodInfoEntity::getFoodId, result.getId());
        } else {
            result = foodTypeEntities.get(0);
            List<String> stringList = foodTypeEntities.stream()
                    .map(FoodTypeEntity::getId)
                    .collect(Collectors.toList());
            lambdaQuery.in(FoodInfoEntity::getFoodId, stringList);
        }
        result.setChildren(lambdaQuery.list());
        return result;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象： <strong>食物信息</strong>
     * @return lambda query chain wrapper
     */
    @NonNull
    private LambdaQueryChainWrapper<FoodInfoEntity> buildLambdaQuery(FoodInfoEntity entity) {
        LambdaQueryChainWrapper<FoodInfoEntity> lambdaQuery = foodInfoService.lambdaQuery();
        return lambdaQuery;
    }

}
